import React from 'react';
import { toJS } from 'mobx';
import { observer } from 'mobx-react';
import { ListViewPage, TabPage } from 'weaver-mobile-page';
import { PullToRefresh } from 'weaver-mobile';
import { Icon, ActivityIndicator, Tools, Result } from 'weaver-mobile';
import messagePageStore from '../store';

const getLabel = Tools.getLabel;

const defaultListParams = {
  id: 0,
  pagesize: 10,
  msgid: 0,
  mintime: 0,
  bizstate: '',
  current: 1
}

@observer
export default class MessagePage extends React.Component{
  scrollDom = null;

  componentDidMount() {
    const {
      updateRead,
      needScroll,
      updateScroll,
      setNeedScroll,
      oldScrollHeight,
      needRefresh
    } = messagePageStore;

    updateRead();

    if (!this.scrollDom) {
      const doms = document.getElementsByClassName('wm-list-view-page-modal-scrollview')
      if (doms.length > 0) {
        this.scrollDom = doms[0];
        this.scrollDom.addEventListener('scroll', this.onScrollHandle.bind(this));
      }
    }
    if (needScroll) {
      setNeedScroll(false);
      updateScroll(oldScrollHeight, needRefresh);
    }

    // if (window.em && window.em.checkJsApi('registerBroadcast')) {
    //   window.em.registerBroadcast({
    //     name: "_closeWfFormCallBack",
    //     action: () => {
    //       this.onRefresh();
    //     }
    //   });
    // } else {
    //   window.__closeFormCallBack = this.onRefresh;
    // }
    
    if (window.em) {
      window.em.ready(() => {
        window.em.appEventListener({'name':'KPageVisibleNotificationName','action':(argument) => {
          //name 关心的事件，1. KBadgeChangedNotificationName 未读数角标变化
          //action 事件回调
          if (typeof(argument) == 'string') {
            try {
              argument = JSON.parse(argument)
            } catch (error) {
              
            }
          }
          if (argument.visible) {
            setTimeout(() => {
              this.onRefresh();
            }, window.reloadCornerDelay || 10)
          }
         },'success':function (res) {
         //注册监听成功
         }
         })
      });
    } else {
      console && console.log('em未加载')
    }
  }

  componentDidUpdate() {
    if (!this.scrollDom) {
      const doms = document.getElementsByClassName('wm-list-view-page-modal-scrollview')
      if (doms.length > 0) {
        this.scrollDom = doms[0];
        this.scrollDom.addEventListener('scroll', this.onScrollHandle.bind(this));
      }
    }
    const { needScroll, updateScroll, setNeedScroll, oldScrollHeight, needRefresh } = messagePageStore;
    if (needScroll) {
      setNeedScroll(false);
      updateScroll(oldScrollHeight, needRefresh);
    }
  }

  onScrollHandle(event) {
    const scrollTop = event.target.scrollTop
    const isTop = (scrollTop === 0)
    const { scrollInTop, setState } = messagePageStore;

    if (isTop) {
      !scrollInTop && setState({scrollInTop: true});
      this.onEndReached();
    } else {
      scrollInTop && setState({scrollInTop: false});
    }
  }

  onEndReached() {
    const { list, getMessageData, loading, hasNoMore, bizstate } = messagePageStore;
    const { current, msgid, mintime } = list;
    const params = {
      current: current + 1,
      pagesize: 10,
      msgid: msgid,
      mintime: mintime,
      bizstate
    }
    if (!hasNoMore && !loading) {
      getMessageData(params, false, true);
    }
  }

  onRefresh = () => {
    const { getMessageData } = messagePageStore;
    let params = { ...defaultListParams }

    getMessageData(params, true, false);
  }

  renderLoading = (
    <div className={`wm-list-view-page-modal-loading`}>
      <ActivityIndicator text="loading..." size="large" />
    </div>
  );

  renderListLoading = (
    <div className={`wm-list-view-page-modal-loading`} style={{marginTop:'45%'}}>
      <ActivityIndicator size="large" />
    </div>
  )

  renderNoMore = (
    <div className={`wm-list-view-page-modal-nomore`}>
      <span className={`wm-list-view-page-modal-nomore-line-left`} />
      <span className={`wm-list-view-page-modal-nomore-line-name`}>{getLabel(390064, '没有更多啦')}</span>
      <span className={`wm-list-view-page-modal-nomore-line-right`} />
    </div>
  );

  getTemplate = (template) => {
    const newTemp = {
      ...template,
      default: [{
        key: 'col_1',
        render: (data) => {
          return (
            <div className={'message-item-wrapper'}>
              <div className={'message-time'}>{data.time}</div>
              { data.showimage && (
                <div
                  className={'message-image'}
                  style={{ backgroundImage: `url(${data.showimage})` }}
                ></div>
              )}
              <div className={'message-item'} onClick={() => {
                if (!data.linkmobileurl){
                  return false;
                }
                if (window.em && window.localStorage.emobile_ec_id) {
                  window.em.checkJsApi("openLink") && window.em.openLink({
                    url: data.linkmobileurl,
                    openType: 2,
                    sysId: window.localStorage.emobile_ec_id,
                    error: function (error) {
                      alert(JSON.stringify(error));
                    }
                  })
                  !window.em.checkJsApi("openLink") && window.open(data.linkmobileurl);
                } else {
                  window.open(data.linkmobileurl);
                }
              }}>
                <div className='message-content-wrapper'>
                  <div className={'message-name'}>{data.name}</div>
                  <div className={'message-title'}
                       dangerouslySetInnerHTML={{ __html: data.title }}
                  ></div>
                  <div className={'message-content'}
                       dangerouslySetInnerHTML={{ __html: data.context }}
                  ></div>
                  {data.bizstate !== '0' && data.bizStateName && <div className='message-status'>{data.bizStateName}</div>}
                </div>
                { data.linkmobileurl  && (
                  <div className={'message-footer'}>
                    <span>{getLabel("503547", "阅读详情")}</span>
                    <Icon color={'#666'} type={'right'} size={'xs'} />
                  </div>
                )}
              </div>
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  render() {
    const {
      list,
      refreshing,
      loading,
      getMessageData,
      tabData,
      tabFlag,
      hasNoMore,
      scrollInTop,
      messagePageIndex,
      isInitMessagePage,
      setState
    } = messagePageStore;

    const tabProps = {
      page: messagePageIndex,
      onTabClick: (tab, index) => {
        this.scrollDom = null;
        let params = { ...defaultListParams };
        setState({
          tabSelectedKey: tab.viewcondition,
          bizstate: tab.msgStateId,
          messagePageIndex: index
        })
        getMessageData(params, true,true);
      },
    };

    if (toJS(list.data).length === 0 && !loading) {
      return (<div className="wm-home-page">
        {tabFlag === '1' && <TabPage
          className="tab-page-example"
          tabs={tabData}
          tabProps={tabProps}
        />}
        <Result
          img={<Icon type={'no-data'} size='lg' />}
          message={getLabel("83553", "暂无数据")}
        />
      </div>)
    }

    let customHeight = tabFlag === '1' ? document.documentElement.clientHeight - 45 : document.documentElement.clientHeight;
    hasNoMore && scrollInTop && (customHeight = customHeight - 34)

    return(
      <div>
        {tabFlag === '1' && (!loading || !isInitMessagePage) && <TabPage
          className="tab-page-example"
          tabs={tabData}
          tabProps={tabProps}
        />}
        <div className="am-list-top">
          {!isInitMessagePage && loading && this.renderLoading}
          {hasNoMore && scrollInTop && this.renderNoMore}
        </div>
        {
          (loading && isInitMessagePage) ? (
            this.renderListLoading
          ) : (
            <ListViewPage.Normal
              className="wm-home-list-view-page"
              store={list}
              getTemplate={this.getTemplate}
              pullToRefresh={<PullToRefresh
                direction='up'
                refreshing={refreshing}
                onRefresh={this.onRefresh}
              />}
              getDataCustom={true}
              customHeight={customHeight}
              heightSpace={this.props.heightSpace}
            />
          )
        }
      </div>
    )
  }
}